<?php

namespace app\api\controller;

use app\api\model\Oauth;
use app\api\model\OauthFocus AS FocusModel;
use app\api\validate\Page;

class OauthFocus extends Base
{
    /**
     * 我的关注
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $page = $data['page'] = input('page') ? input('page') : 1;
        $size = $data['size'] = input('size') ? input('size') : $this->pageSize;

        // 检测变量
        $validate = new Page();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        $oauthId = $this->oauthInfo['id'];
        $model = FocusModel::getList($oauthId, $page, $size);
        return self::sendResult(self::$okCode, $model);
    }

    /**
     * 关注
     * @param $focusId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create($focusId)
    {
        if ($focusId < 0) {
            return self::sendResult(100);
        }

        $oauthId = $this->oauthInfo['id'];

        if ($oauthId == $focusId) {
            return self::sendResult(113, [], '不能自己关注自己');
        }

        // 查找要关注的用户是否存在
        $focus = Oauth::getOne($focusId);
        if (empty($focus)) {
            return self::sendResult(110);
        }

        // 查看是否已经关注过该用户
        $model = FocusModel::getOne($oauthId, $focusId);
        if ($model) {
            return self::sendResult(111, [], '您已经关注过了');
        }

        // 添加点赞或者收藏记录
        $res = FocusModel::addOne($oauthId, $focusId);
        if ($res === true) {
            $code = self::$okCode;
            $msg = '关注成功';
        } else {
            $code = 113;
            $msg = '关注失败';
        }
        return self::sendResult($code, [], $msg);
    }

    /**
     * 取消关注
     * @param $focusId
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($focusId)
    {
        if ($focusId < 0) {
            return self::sendResult(100);
        }

        $oauthId = $this->oauthInfo['id'];

        // 查找要关注的用户是否存在
        $model = FocusModel::getOne($oauthId, $focusId);
        if (empty($model)) {
            return self::sendResult(110, [], '您还未关注该用户');
        }


        // 删除点赞或者收藏记录
        FocusModel::deleteOne($oauthId, $focusId);

        return self::sendResult(self::$okCode, [], '取消关注成功');
    }
}